import filedict
import sys
import settings

from wikiqueries import translation_by_iwiki,toU

iwikis = filedict.FileDict("dictionaries/iwikis")
redirs = filedict.FileDict("dictionaries/enredirects")
personames = filedict.FileDict("dictionaries/personames")
othersegments = filedict.FileDict("dictionaries/other")

def upper1(s): 
	""" Upcase first letter """
	if s:
		return s[0].upper()+s[1:]
	else:
		return s

def lower1(s): 
	""" Upcase first letter """
	if s:
		return s[0].lower()+s[1:]
	else:
		return s

def isname(s):
	l = s.split(" ")
	for n in l:
		if n not in personames:
			return False
	return True
def transname(s):
	l = s.split(" ")
	rl = []
	for n in l:
		rl.append(personames[n])
	return " ".join(rl)

def hand_translate(s):
	if settings.no_hand_translate:
		return s
	print 'input translation of "%s". \nBegin translation with # if it is person name. Begin with [ if it will be article name' % s
	tr = raw_input("> ").decode(settings.terminal_cp)
	if len(tr)<1:
		return s
	if tr[0]=="#":
		res = tr[1:]
		trl = res.split(" ")
		sl = s.split(" ")
		for s,t in zip(sl,trl):
			personames[s]=t
		return res
	elif tr[0]=="[":
		res = tr[1:]	
		iwikis[s] = res
		return res
	else:
		othersegments[s] = tr
		return tr

def translate_capitalized(s):
	""" translate segment which must be capitalized """
	if s in iwikis:
		return iwikis[s]

	if s in redirs:
		return translate_capitalized(redirs[s])
	if isname(s):
		return transname(s)	
	if s in othersegments:
		return othersegments[s]

	trans = translation_by_iwiki(s,"en","uk")
	if trans:
		iwikis[s] = trans
		return trans
	return hand_translate(s)

def translate(s):
	if not s:
		return ""
	if len(s)<1:
		return ""
	toU(s)
	seg = upper1(s)
	upcased= seg!=s

	seg = translate_capitalized(seg)
	if upcased:
		return lower1(seg)
	else: 
		return seg
	


if __name__=="__main__":
	if len(sys.argv)<2:
		seg = raw_input("Input segment to translate:")
	else:
		seg = sys.argv[1]
	print translate(seg)
